﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Drawing.Printing;

using UploadManager;
//using StoreClientModule;
using UnityCore;

namespace MBBStoreClient
{
    public partial class frmPriceListViewer : Form
    {
        //PriceListViewer plv = new PriceListViewer();

        SynchronizeData sync = new SynchronizeData();
        Threader t = new Threader();
        readDetails path = new readDetails();
        DataTable exportPriceList = new DataTable();
        DataTable exportProducts = new DataTable();
        priceDetails pD = new priceDetails();

        public frmPriceListViewer()
        {
            InitializeComponent();

            btnClose.Click += new EventHandler(btnClose_Click);
            panel2.EnabledChanged += new EventHandler(panel2_EnabledChanged);

            btnRefresh.Click += new EventHandler(btnRefresh_Click);
            grdList.Sorted += new EventHandler(grdList_Sorted);
            btnPrint.Click += new EventHandler(btnPrint_Click);
            btnSearch.Click += new EventHandler(btnSearch_Click);
            txtSearch.KeyPress += new KeyPressEventHandler(txtSearch_KeyPress);

            sync.ProcessCompleted += new UnityCore.CoreHandler(sync_ProcessCompleted);
            sync.ProcessError += new UnityCore.CoreHandler(sync_ProcessError);
        }

        void sync_ProcessError(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(msg);
            });
        }

        void sync_ProcessCompleted(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                switch (pcode)
                {
                    case "ReadMany":
                        exportPriceList= sync.exportTables[0];
                        exportProducts = sync.exportTables[1];

                        FormatGrid();
                        pD.tables.Add(exportPriceList);
                        pD.tables.Add(exportProducts);
                        sync.extract(pD);
                        break;
                    case "ExtractPriceList":
                        grdList.DataSource = sync.pPriceList;
                        pnlMsg.Visible = false;
                        break;
                }

            });
        }

        void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                btnSearch_Click(sender, e);
            }
        }

        void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
               pnlMsg.Visible = true;
                for (int r = grdList.SelectedRows[0].Index + 1; r < grdList.Rows.Count; r++)
                {
                    for (int c = 0; c < grdList.Columns.Count; c++)
                    {
                        if (grdList.Rows[r].Cells[c].Value.ToString().ToUpper().Contains(txtSearch.Text.ToUpper()))
                        {
                            grdList.Rows[r].Selected = true;
                            grdList.FirstDisplayedScrollingRowIndex = r;
                            pnlMsg.Visible = false;
                            return;
                        }
                    }
                }
                pnlMsg.Visible = false;
                
            }
            catch (Exception ex)
            {
               // pnlMsg.Visible = false;
            }
        }
        int cnt = 1;
        int pp = 1;
        void btnPrint_Click(object sender, EventArgs e)
        {
            PrintDocument pd = new PrintDocument();
            pd.DocumentName = lblText.Text;
            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            PrintDialog pdlg = new PrintDialog();
            pdlg.Document = pd;
            if (pdlg.ShowDialog() == DialogResult.OK)
            {
                PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                ppdlg.Document = pd;
                ppdlg.ShowDialog();
            }
        }

        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float lpp = 0;
            float y = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.MarginBounds.Left;
            float rm = e.PageBounds.Width - 100;
            float bm = e.PageBounds.Height - 100;
            float ht = 0;
            Font cFont;
            StringFormat sf = new StringFormat();


            //Header
            y = 50;
            cFont = new Font("Courier New", 11f, FontStyle.Bold);
            ht = cFont.GetHeight(e.Graphics);
            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Price List - Page "+ pp, cFont, Brushes.Black, lm, y, sf);
            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString(DateTime.Now.ToShortDateString(), cFont, Brushes.Black, rm, y,sf);
            //Column Header
            y += ht;
            e.Graphics.FillRectangle(Brushes.LightGray, lm, y, rm - lm, ht);
            e.Graphics.DrawRectangle(new Pen(Brushes.Black), lm, y, rm-lm, ht);
            sf.Alignment = StringAlignment.Center;
            float cx = lm + (((rm - lm) * 25) / 100);
            float tx = lm + (((rm - lm) * 12.5f) / 100);
            //e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            //e.Graphics.DrawString("Barcode", cFont, Brushes.Black, tx, y, sf);
            cx += ((rm - lm) * 20) / 100;
            tx = cx - ((rm - lm) * 20) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            //e.Graphics.DrawString("Description", cFont, Brushes.Black, tx, y, sf);
            cx += ((rm - lm) * 15) / 100;
            tx = cx - ((rm - lm) * 15) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Variation", cFont, Brushes.Black, tx, y, sf);
            cx += ((rm - lm) * 20) / 100;
            tx = cx - ((rm - lm) * 20) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("P.Code", cFont, Brushes.Black, tx, y, sf);
            tx += ((rm - lm) * 20) / 100;
            e.Graphics.DrawString("SRP", cFont, Brushes.Black, tx, y, sf);
            //Data
            y += ht * (1.5f);
            cFont = new Font("Courier New", 11f, FontStyle.Regular);
            ht = cFont.GetHeight(e.Graphics);
            lpp = (bm - y) / ht;
            int cl = 0;
            while (cl <= lpp && cnt < grdList.Rows.Count)
            {
                sf.Alignment = StringAlignment.Near;
                float stx = lm + 1;
                string str = grdList.Rows[cnt].Cells["fBarcode"].Value.ToString();
                if (!str.Equals(""))
                {
                    e.Graphics.FillRectangle(Brushes.Yellow, lm, y, rm - lm, ht);
                }
                if (str.Equals("Supplier :"))
                {
                    e.Graphics.FillRectangle(Brushes.LightGray, lm, y, rm - lm, ht);
                }
                if (str.Length > 21)
                {
                    str = str.Substring(0, 18) + "...";
                }
                e.Graphics.DrawString(str, new Font("Courier New", 10f, FontStyle.Regular) , Brushes.Black, stx, y, sf);
                stx += ((rm - lm) * 30) / 100;
                str = grdList.Rows[cnt].Cells["fDescription"].Value.ToString();
                if (str.Length > 45)
                {
                    str = str.Substring(0, 42) + "...";
                }
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                stx += ((rm - lm) * 15) / 100;
                str = grdList.Rows[cnt].Cells["fVariation"].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                sf.Alignment = StringAlignment.Far;
                stx += ((rm - lm) * 35) / 100;
                str = grdList.Rows[cnt].Cells["fPcode"].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Red, stx, y, sf);
                stx += ((rm - lm) * 20) / 100;
                str = grdList.Rows[cnt].Cells["fMarkUp"].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                y += ht;
                cnt++;
                cl++;
            }
            if (cnt < grdList.Rows.Count)
            {
                e.HasMorePages = true;
                pp++;
            }
            else
            {
                e.HasMorePages = false;
                cnt = 1;
                pp = 1;
            }
        }

        void grdList_Sorted(object sender, EventArgs e)
        {
            //plv.GetPriceList();
        }
        void btnRefresh_Click(object sender, EventArgs e)
        {
           // plv.GetPriceList();
        }
        
        void FormatGrid()
        {
            try
            {
                grdList.Columns[0].HeaderText = "Barcode";
                grdList.Columns[1].HeaderText = "Description";
                grdList.Columns[2].HeaderText = "Variation";
                grdList.Columns[3].HeaderText = "P.Code";
                grdList.Columns[4].HeaderText = "SRP";
                grdList.Columns[1].Width = (grdList.Width * 30) / 100;
                grdList.Columns[3].DefaultCellStyle.ForeColor = Color.Red;
                grdList.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                grdList.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                grdList.Columns[0].HeaderCell.SortGlyphDirection = SortOrder.None;

                grdList.Rows[0].Cells[4].Style.ForeColor = Color.Black;
                for (int i = 0; i < grdList.Columns.Count; i++)
                {
                    grdList.Rows[0].Cells[i].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    grdList.Rows[0].Cells[i].Style.BackColor = Color.Gray;
                }
                grdList.Font = new Font("Courier New", 10);
            }
            catch (Exception ex)
            {
            }
        }
        

        void panel2_EnabledChanged(object sender, EventArgs e)
        {
            if (!panel2.Enabled)
            {
                panel2.BackColor = Color.MidnightBlue;
            }
            else
            {
                panel2.BackColor = Color.RoyalBlue;
            }
        }
        void btnClose_Click(object sender, EventArgs e)
        {
            pnlForm.Dispose();
            this.Dispose();
        }
        public Panel PanelForm
        {
            get { return pnlForm; }
        }
        public void Initialize(string Title)
        {
            this.Select();
            lblText.Text = Title;
            path.fileNames = new List<string>();
            pD.tables = new List<DataTable>();
            pnlMsg.Visible = true;
            //plv.GetPriceList();

            path.date = "";
            path.remNode = "mbb_warehouse";
            path.fileNames.Add("tblpricelist");
            path.fileNames.Add("tblproducts");
            sync.ReadMany(path);
        }
    }
}
